﻿using ContactApp.DataModels;
using ContactApp.Db;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ContactApp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            List<Contact> contacts;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                contacts = db.Contacts.ToList();
            }
            return View(contacts);
        }
        [HttpGet]
        public ActionResult AddContact()
        {
            

            return View();
        }
        [HttpPost]

        public ActionResult AddContact(string firstName, string lastName, string title, string phoneNumber)
        {
            using(ApplicationDbContext db = new ApplicationDbContext())
            {

                db.Contacts.Add(new Contact() {FirstName=firstName, LastName=lastName, Title=title, PhoneNumber=phoneNumber });
                db.SaveChanges();
            }

            return RedirectToAction("Index");
        }
        [HttpPost]
        public ActionResult DeleteContact(int id)
        {

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                Contact contact = db.Contacts.Find(id);
                db.Contacts.Remove(contact);
                db.SaveChanges();
            
            }
            return RedirectToAction("Index");
        
        }
        [HttpGet]
        public ActionResult EditContact(int id)
        {
            Contact contact;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {

                contact = db.Contacts.Find(id);
            }
            return View(contact);
        }
        [HttpPost]
        public ActionResult EditContact(string firstName, string lastName, string title, string phoneNumber, int id)
        {
            Contact contact;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                contact = db.Contacts.Find(id);
                contact.FirstName = firstName;
                contact.LastName = lastName;
                contact.Title = title;
                contact.PhoneNumber = phoneNumber;
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }
    }
}